
<template>
  <div class="common_block_div">
    <div class="">
      <div class=" ">
      <el-form :model="queryParams" class="margin_t10" ref="queryForm"  label-width="90px">
        <el-row class="flex flex_w">
          <FormItem label="人员名称" class="" type="input" :form="queryParams"  placeholder="姓名、账号等" @keyenter="handleQuery" prop="keywords" clearable />
          <el-col :span="0.1">
            <el-form-item label="所属部门" prop="organization">
                <el-cascader style="width:100%" v-model="queryParams.organization" :options="group_list" filterable
                    :props="{ expandTrigger: 'hover',checkStrictly: true,emitPath:false,value:'id',label:'org_name',children:'children'}"
                    clearable></el-cascader>
            </el-form-item>
          </el-col>
          <FormItem label="角色类型" class="" type="select" :form="queryParams" prop="role" :seleDatas="role_list2" seleKey="id" seleName="role_name" clearable filterable />
          <div class="search_btns pad_l20">
            <el-button type="primary" icon="el-icon-search" @click="handleQuery">搜索</el-button>
            <el-button icon="el-icon-refresh"  @click="resetQuery">重置</el-button>
          </div>
        </el-row>
      </el-form>
      <div class="common_button flex_ac">
        <div class="right_button margin_a flex">
          <a href="javascript:;" class="color_blue" @click="handleUpdate" v-if="have_auth('/system/user/add')">新增</a>
          <!-- <a href="javascript:;" class="color_orange" @click="try_export_data" v-if="have_auth('/system/user/export')"><img src="@/assets/export.png" class="btn_img">{{is_download?'导出中···':'导出'}}</a> -->
          <!-- <a href="javascript:;" class="color_red" @click="handleDelete" v-if="have_auth('/system/user/del')">删除</a> -->
        </div>
      </div>


      <el-table v-loading="loading" :data="list"  border @selection-change="handleSelectionChange">
         <!-- :selectable="selectable_fun" -->
        <!-- <el-table-column type="selection" width="55" align="center" :selectable="selectable_fun" /> -->
        <el-table-column label="用户ID" align="center" prop="id"  />
        <el-table-column label="姓名" align="center" prop="realname"  />
        <el-table-column label="登录账号" align="center" prop="username"  />
        <el-table-column label="所属部门" align="center" width="300" :show-overflow-tooltip="true">
          <template slot-scope="scope">
            {{scope.row.company_title}}
          </template>
        </el-table-column>
        <el-table-column label="角色" align="center" prop="id">
          <template slot-scope="scope">
            {{scope.row.role_title}}
          </template>
        </el-table-column>
        <el-table-column label="状态" align="center" prop="status">
          <template slot-scope="scope">
            <el-switch v-model="scope.row.status" :disabled="scope.row.id==1 || !have_auth('/system/user/edit')" @change="sw_change($event,scope.row)" :active-value="1" :inactive-value="0"></el-switch>
          </template>
        </el-table-column>
        <el-table-column label="创建时间" align="center" prop="create_time" width="180" />
        <!-- <el-table-column label="更新时间" align="center" prop="update_time" width="180" /> -->
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="120px" fixed="right">
          <template slot-scope="scope">
            <el-button type="text" size="small" @click="handleUpdate(scope.row)" v-if="scope.row.id!=1 && have_auth('/system/user/edit')">编辑</el-button>
            <el-button type="text" size="small" @click="handleDelete(scope.row)" v-if="scope.row.id!=1  && have_auth('/system/user/del')">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <pagination
        v-show="total>0"
        :total="total"
        :page.sync="queryParams.page"
        :limit.sync="queryParams.limit"
        @pagination="getList"
      />
    </div>
    </div>
    <!-- 添加或修改对话框 -->
    <el-dialog v-dialogDrag :close-on-click-modal="false" title="新增/编辑用户" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-row>
          <FormItem label="姓名" class="" :span="24" type="input" :form="form" prop="realname" clearable />
          <FormItem label="登录账号" class="" :span="24" type="input" :form="form" prop="username" clearable />
          <el-col :span="24">
            <el-form-item label="所属部门" prop="organization_id">
                <el-cascader style="width:100%" v-model="form.organization_id" :options="group_list" filterable
                    :props="{ expandTrigger: 'hover',checkStrictly: true,emitPath:false,value:'id',label:'org_name',children:'children'}"
                    clearable></el-cascader>
            </el-form-item>
          </el-col>
          <FormItem label="角色类型" class="" :span="24" type="select" :form="form" prop="role_ids" :seleDatas="role_list2" seleKey="id" seleName="role_name" clearable filterable />

          <el-col :span="24">
            <el-form-item label="登录密码" prop="password">
            	<el-input v-model="form.password" placeholder="请输入登录密码" type="password"></el-input>
            </el-form-item>
          </el-col>
          <FormItem label="是否启用" class="" :span="24" type="radioss" radioyes="启用" radiono="禁用" :form="form" prop="status" clearable />
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="open=false;">取 消</el-button>
        <el-button type="primary" @click="submitForm('form')" :loading="is_ajax">{{is_ajax?'保存中···':'确定'}}</el-button>
      </div>
    </el-dialog>



    <!-- 上传图片预览 -->
    <el-dialog  :close-on-click-modal="false" append-to-body @closed="uploadImageUrl=''" width="600px" :visible.sync="uploadImgVisible">
      <img style="width: 100%;" :src="uploadImageUrl" alt="">
    </el-dialog>
    <a href="" class="js_download"></a>
  </div>
</template>

<script>
  import $ from "jquery";
// 上传组件
import SigleUpload from "@/components/UploadImage/sigleUpload";
export default {
  name: 'needCache',
  components: {SigleUpload},
  data () {
    return {
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      activeName:'1',  // 1进行中 2 已结束
      loading: true,
      total: 0,
      // 定时任务表格数据
      list: [],
      // 查询参数
      queryParams: {
        page: 1,
        limit: 16,
        keywords: '',
        organization: '',
        role: ''
      },
      openOptions: [{id:'1',title:'选项1'},{id:'2',title:'选项2'}],
      gender_list: [{id:1,title:'男'},{id:2,title:'女'}],
      open:false,
      // 表单参数
      form: {
        realname:'',
        username:'',
        organization_id:"",
        role_ids:'',
        password:'',
        status:1
      },
      // 表单校验
      rules: {
        realname: [
          { required: true, message: "姓名不能为空", trigger: "blur" }
        ],
        username: [
          { required: true, message: "登录账号不能为空", trigger: "blur" }
        ],
        organization_id: [
          { required: true, message: "所属部门不能为空", trigger: "blur" }
        ],
        role_ids: [
          { required: true, message: "角色类型不能为空", trigger: "blur" }
        ],
        password: [
          { required: true, message: "登录密码不能为空", trigger: "blur" }
        ]
      },
      is_ajax:false,
      group_list:[],
      unit_list:[],
      role_list:[],
      role_list2:[],
      pj_list:[],
      par_list:[],
      // 上传图片
      uploadImageUrl: '',
      uploadImgVisible: false,
      is_download:false
    }
  },
  activated() {
    this.getList();
    this.get_options()
  },
  methods:{
    // try_export_data(){
    //   const _this=this;
    //   if(_this.is_download){return false;}
    //   _this.is_download=true
    //   _this.axios.get("/api/User/export", {params:this.queryParams}).then(function(res) {
    //      if(res){

    //         $(".js_download")
    //           .attr("href",_this.http+res.message.link)
    //           .attr("download", res.message.link.split('/export/')[1]);
    //         $(".js_download")[0].click();
    //      }
    //      _this.is_download=false
    //   }).catch(function(error) {
    //     console.log(error);
    //     _this.is_download=false
    //   })
    // },
    // 上传图片--s
    PicturePreview(file) {
      this.uploadImageUrl = file.url;
      this.uploadImgVisible = true;
    },
    handleUploadSuccess(res){
      console.log(res)
      this[res.form]['idcard_image_id']=res.id
      this[res.form][res.key]=res.url
    },
    handleUploadRemove(res){
      this[res.form][res.key]=''
    },
    sw_change(e,row){
      const _this=this;
      row.status=e;
      let _data={...row};
      _data.password='';
      let url="/manage/admin.User/save";
      _this.axios.post(url, _data).then(function(data) {
        if(data){
          _this.tip_show('操作成功','success');
          // _this.getList()
        }
        _this.is_ajax=false;
      }).catch(function(error) {
        _this.is_ajax=false
        console.log(error);
      })

    },
    selectable_fun(row){
        if(row.id==1){
            return false;
        }
        return true
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id);
      this.single = selection.length != 1;
      this.multiple = !selection.length;
    },
    handleDetail(row){
      this.$store.commit('set_cur_pro',row)
      this.$router.push({ //核心语句
        path: '/project/sampling?id='+row.id,
      })
    },
    // 表单重置
    reset() {
      this.form = {is_hid:0,idcard_image:'',role_id:''};
      if(this.$refs['form']){
        this.$refs['form'].clearValidate();
      }
    },
    /** 提交按钮 */
    submitForm: function(form) {
      const _this=this;
      this.$refs[form].validate(valid => {
        if (valid) {
          this.is_ajax=true;
          let _data={..._this[form]};
          let url="/manage/admin.User/save";
          _this.axios.post(url, _data).then(function(data) {
            if(data){
              _this.tip_show('操作成功','success');
              _this.open=false;
              _this.getList()
            }
            _this.is_ajax=false;
          }).catch(function(error) {
            _this.is_ajax=false
            console.log(error);
          })
        }
      });
    },

    get_options(){
      const _this=this;
      _this.axios.get("/manage/admin.Organization/index", {params:{limit: 169999999}}).then(function(res) {
        if(res){
          _this.group_list = res.message
        }
      }).catch(function(error) {
        console.log(error);
      })

      _this.axios.get("/manage/admin.Role/index", {params:{limit: 169999999}}).then(function(res) {
        if(res){
          _this.role_list2 =res.message.data;
        }
      }).catch(function(error) {
        console.log(error);
      })
    },
    /** 查询定时任务列表 */
    getList() {
      const _this=this;
      this.loading = true;
      _this.axios.get("/manage/admin.User/index", {params:this.queryParams}).then(function(res) {
        if(res){
          _this.list = res.message.data;
          _this.total = res.message.total;
          _this.loading = false;
          // _this.openOptions=_this.obj2arr(res.message.search.status)
        }
      }).catch(function(error) {
        console.log(error);
      })
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.page = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.queryParams={
        page: 1,
        limit: 16,
        keywords: '',
        organization: '',
        role: ''
      }
      this.handleQuery();
    },
    /** 修改按钮操作 */
    handleUpdate(row){
      this.reset()
      let form=row.id?{...row}:{
        realname:'',
        username:'',
        organization_id:"",
        role_ids:'',
        password:'',
        status:1
      };

      if(form.id){
        this.rules.password[0].required=false;

        form.password='';
        form.role_ids=parseInt(form.role_ids)
      }else{
        this.rules.password[0].required=true
      }
      this.form={...form}

      console.log(this.form)
      this.open=true;
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const _this=this;
      const ids = row.id;
      if(ids.length==0){
        _this.$message.error('请选择要操作的数据');
        return false;}
      this.$confirm('是否确认删除?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          _this.axios.post("/manage/admin.User/delete", {id:ids}).then((res) => {
              if (res) {
                  _this.getList();
                  _this.$message.success('操作成功');
              }
          }).catch((err) => {
              console.log(err);
          });
        })
    },

  }
}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
  .title{line-height: 44px; font-size: 20px;}
</style>
